<template>

  <div class="app-container" style="font-size:12px">
    <div class="filter-container">
      <!-- <el-date-picker v-model="listQuery.date1" style="width:150px;" format="yyyy-MM-dd" type="datetime" placeholder="订单开始日" />
      <el-date-picker v-model="listQuery.date2" style="width:150px" format="yyyy-MM-dd" type="datetime" placeholder="订单结束日" /> -->
      <el-input v-model="listQuery.customer" placeholder="客户姓名" style="width: 100px;margin-top:6px" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.c_id" placeholder="选择门店" filterable class="filter-item" style="width:150px;margin-top:8px">
        <el-option label="选择门店" value="" />
        <el-option
          v-for="item in company_list"
          :key="item.id"
          :label="item.c_name"
          :value="item.id"
        />
      </el-select>

      <el-select v-model="listQuery.shareholder" placeholder="股东" class="filter-item" style="width:130px;margin-top:8px">
        <el-option label="股东" value="" />
        <el-option
          v-for="item in shareholderList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <admini ref="admini" />
    
      <el-select v-model="listQuery.ds_status" placeholder="待收状态" style="width: 180px">
        <el-option label="收回" :value="1" />
        <el-option label="提前结清" :value="2" />
        <el-option label="疑难" :value="3" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-top:6px" @click="handleFilter">查询</el-button>
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-top:8px" @click="excelout">导出</el-button> -->
      <excel />
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini" :row-class-name="tableRowClassName" border fit highlight-current-row style="width: 100%;margin-top:20px">
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template v-if="row.is_paid!=1" slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="outcome(row.order_id)">
            支出
          </el-button>
          <el-button type="success" size="mini" @click="plan(row.order_id)">
            租金计划
          </el-button>
          <el-button type="info" size="mini" @click="detail(row.order_id)">
            详情
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="编号" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.order_contract_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="门店" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.c_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="租车日期" align="center" width="100px">
        <template slot-scope="{row}">
          {{ row.create_time }}
        </template>
      </el-table-column>

      <el-table-column label="客户名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.real_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="客户电话" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证" align="center" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.idcard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" width="100px">
        <template slot-scope="{row}">
          {{ row.plate_no }}
        </template>
      </el-table-column>
      <el-table-column label="融资金额" align="center" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.total_price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="每期租金" align="center">
        <template slot-scope="{row}">
          <span>{{ row.a_month_price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总期数" align="center" width="70px">
        <template slot-scope="{row}">
          <span>{{ row.total_period }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已付期数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.payed_num }}</span>
        </template>
      </el-table-column>

      <el-table-column label="应收总额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.all_price }}</span>
        </template>
      </el-table-column>

     
      <el-table-column label="已付金额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.paid_money }}</span>
        </template>
      </el-table-column>

      <el-table-column label="未付金额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.no_paid_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余加融" align="center">
        <template slot-scope="{row}">
          <span>{{ row.overdue_rate_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余本金" align="center">
        <template slot-scope="{row}">
          <span>{{ row.no_paid_benjin }}</span>
        </template>
      </el-table-column>

    
      <el-table-column label="提前结清金额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.before_settle_money }}</span>
        </template>
      </el-table-column>

      <el-table-column label="累计逾期天数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.all_overdue_days }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注信息" align="center" width="200">
        <template slot-scope="{row}">
          <span>{{ row.descript }}</span>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogRecordAble" class="abow_dialog" title="跟进记录" width="750px">
      <collectForm v-if="addStatus" :order_id="form.order_id" @cancel="addStatus=false;" />
      <div class="radio">
        跟进记录：
        <el-button v-if="addStatus==false" type="primary" round size="mini" @click="addStatus=true">新增记录</el-button>
      </div>
      <collectRecord v-if="dialogRecordAble&&addStatus==false" :order_id="form.order_id" />
    </el-dialog>
    <el-dialog title="租金计划" :visible.sync="dialogPlanAble" style="width:1500px;margin:auto">
      <table class="flowtable">
        <tr>
          <th>期数</th>
          <th>应付日期</th>
          <th>应付金额</th>
          <th>实付金额</th>
          <th>实付日期</th>
          <th>加融金额</th>
          <th>逾期天数</th>

          <th>付租状态</th>
        </tr>
        <tr v-for="(item,index) in plan_list" :key="index">
          <td>{{ item.num }}</td>
          <td>{{ item.time_date }}</td>
          <td>{{ item.total_money }}</td>
          <td>{{ item.paid_money }}</td>
          <td>{{ item.sh_time }}</td>
          <td>{{ item.money_rate }}</td>
          <td>{{ item.late_num }}</td>

          <td>{{ item.status_name }}</td>
        </tr>
      </table>
      <pagination v-show="plan_total>0" :total="plan_total" :page.sync="planQuery.page" :limit.sync="planQuery.limit" @pagination="planList" />
    </el-dialog>
    <el-dialog title="报销信息" :visible.sync="expenseaddAble" v-dialog-drag   class="create" :fullscreen="true">
        <el-form ref="dataForm" :model="add_form" label-width="45%" >
          <el-form-item label="费用类型" style="width:75%;">
            <el-select v-model="add_form.money_type" placeholder="费用类型" >
              <el-option
                v-for="item in type_list.money_type"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="报销金额" style="width:75%;">
            <el-input v-model="add_form.settle_money" type="number"/>
          </el-form-item>
          <el-form-item label="费用组成" style="width:75%;">
            <el-input v-model="add_form.money_combi" type="text"/>
          </el-form-item>
          <el-form-item label="图片上传" style="width:75%;">
            <el-upload
            class="upload-demo"
            :action="action"
            :headers="myHeaders"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="uploadSuccess"
            multiple
            list-type="picture"
            :limit="50"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
          </el-form-item>
          
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAdd()">添加</el-button>
      </span>
      </el-dialog>
    <el-dialog title="支出" :visible.sync="outComedAble"  v-dialog-drag  class="create" :fullscreen="true">
      <div  class="l_title">报销信息</div>
        <el-card class="box-card" style="margin-top: 20px;" v-for="(item,index) in expenselist" :key="index">
          <el-row >
            <el-col :span="7">报销类型：{{ item.expense_name }}</el-col>
            <el-col :span="7">报销金额：{{ item.money }}</el-col>
            <el-col :span="8">费用组成：{{ item.money_combi }}</el-col>
            <el-col :span="2"><span class="el-icon-delete" @click="deleteOneExpense(item.id)" style="color:orangered;cursor: pointer;"></span></el-col>
          </el-row> 
          <el-row style="margin-top: 20px;">
            <el-col :span="24">图片信息</el-col>
            <el-col :span="24">
              <div ref="viewer" v-viewer="viewerOptions" class="">
                <div v-for="(img,index1) in item.att" :key="index1" class="grid-content bg-purple-light img_box">
                  <div class="hovers">{{ item.field }}</div>
                  <img :src="img.path" height="100%" width="100%">
                </div>
               
              </div>
            </el-col>
          </el-row> 
        </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="expense()">新增</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import excel from '@/components/excelout/index.vue'
import {
  getManagerType,expenseList,expenseAddByDs,deleteOneExpense
} from '@/api/manager'
import admini from '@/components/company/admin.vue'
import {
  financeOrderList, exceloutfinance, returnOrderSubmit, serverAllMoneySubmit, orderShareHolderSet, getShareHolder, getThisOrderShareHolder, paymentList
} from '@/api/finance'
import { formatDate } from '@/utils/formatDate.js'
import { merchantListOnlyMerchant } from '@/api/merchant'
import collectForm from '@/components/collect/form.vue'
import collectRecord from '@/components/collect/index.vue'
import { fetchList } from '@/api/sale'
import waves from '@/directive/waves' // waves directive
import {
  parseTime
} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'ComplexTable',
  components: {
    Pagination, excel, collectRecord, collectForm,admini
  },
  directives: {
    waves
  },
  filters: {
   	formatDate(time) {
   	        time = time * 1000
   	        const date = new Date(time)

   	        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
   	      }
  },
  data() {
    return {
      fileList:[],
      expenselist:[],
      expense_order_id :'',
      type_list:[],
      outComedAble:false,
      expenseaddAble:false,
      add_form:{
          file_id:'',
          money_type:''
        },
      dialogPlanAble: false,
      shareQuery: {
        limit: 100
      },
      status_form: {
        status: 0
      },
      plan_list: [],
      listRecordLoading: true,
      recordTotal: 0,
      dialogRecordAble: false,
      shareholderList: [],
      other_form: {
        order_id: '',
        money: '',
        desc: '',
        incidental_money: '',
        outcome_money: '',
        status: '0',
        contract_outcome: 0,
        contract_income: 0,
        contract_outcome_date: '',
        contract_income_date: ''
      },
      shareholder_from: {
        order_id: '',
        datas: [
          {
            shareholder: '',
            money: '',
            percentage: '',
            benefits: ''
          }
        ]
      },
      planQuery: {
        page: 1,
        limit: 10
      },
      myHeaders: {
          token: this.$store.getters.token
        },
      action: process.env.VUE_APP_BASE_API + '/backend_upload',
      addStatus: false,
      changeStatusAble: false,
      tableKey: 0,
      shareholderAble: false,
      descAble: false,
      outcomeInputAble: false,
      incidentalAble: false,
      tableRecord: 1,
      list: null,
      record_list: null,
      listRecordLoading: true,
      recordTotal: 0,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        customer: '',
        order_status: '4',
        c_id: '',
        sale_id: '',
        excel: 0,
        flag: 1,
        date1: '',
        date2: '',
        shareholder: ''
      },
      listMerchantQuery: {
        page: 1,
        limit: 500
      },
      company_list: [],
      sale_list: [],
      form: [],
      plan_total: ''
    }
  },
  created() {
    this.getShareHolder()
    this.listQuery.shareholder = this.$route.query.shareholder
    this.getCompanyList()
    this.getList();
    getManagerType(this.listQuery).then(response => {
          this.type_list = response.data
        })
  },

  methods: {
    planList() {
      paymentList(this.planQuery).then(response => {
        this.plan_list = response.data.list.data
        this.plan_total = response.data.list.total
        this.listLoading = false
      })
    },
    deleteOneExpense(id){
      console.log(id)
      this.$confirm('确定删除吗, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let pam = {id:id}
            deleteOneExpense(pam).then(response => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.expenseList(this.expense_order_id)
            })
            this.detailAble = false;;
            this.getList();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消操作'
            });          
          });
    },
    expense(id){
      this.expenseaddAble = true;
    },
    doAdd(){
      for(let i=0;i<this.fileList.length;i++){
          this.add_form.file_id += this.fileList[i].id+','
        }
        this.add_form.order_id = this.expense_order_id
      expenseAddByDs(this.add_form).then(response => {
        this.expenseaddAble = false;
        this.expenseList(this.expense_order_id)
        this.add_form = {};
        this.add_form.order_id = this.expense_order_id
        this.fileList = [];
      })
    },
    outcome(id){
      this.outComedAble = true;
      this.expense_order_id = id;
      this.expenselist = [];
      this.expenseList(id)
    },
    expenseList(id){
      let pam = {order_id:id}
      expenseList(pam).then(response => {
        this.expenselist = response.data.data[0].expense;
      })
    },
    detail(order_id) {
      this.$router.push('/order/detail/' + order_id)
    },
    record(order_id) {
      this.dialogRecordAble = true
      this.form.order_id = order_id
    },
    addDocument() {
      const o = { shareholder: '', money: '', percentage: '' }
      this.shareholder_from.datas.push(o)
    },
    getShareHolder(order_id) {
      getShareHolder(this.shareQuery).then(response => {
        this.shareholderList = response.data.data
      })
      this.getThisOrderShareHolder(order_id)
    },
    getThisOrderShareHolder(order_id) {
      const pam = { order_id: order_id }
      getThisOrderShareHolder(pam).then(response => {
        // this.thisOrderShareholder = response.data.data;
        this.shareholder_from.datas = [
          {
            shareholder: '',
            money: '',
            percentage: '',
            benefits: ''
          }
        ]
        if (response.data.length > 0) {
          this.shareholder_from.datas = response.data
        }
      })
    },
    delDocument(k) {
      this.shareholder_from.datas.map((item, index) => {
        if (index == k) {
          this.shareholder_from.datas.splice(index, 1)
        }
      })
    },

    getList() {
      financeOrderList(this.listQuery).then(response => {
        if (!this.listQuery.excel) {
          this.list = response.data.list.data
          this.total = response.data.list.total
          this.allcount = response.data.countall

          setTimeout(() => {
            this.listLoading = false
          }, 0.1 * 1000)
        } else {
          this.listQuery.excel = 0
        }
      })
    },
    outcomeInput(order_id, row) {
      this.outcomeInputAble = true
      this.other_form.order_id = order_id
      this.other_form.outcome_money = row.outcome_money
    },
    changeStatus(order_id, row) {
      this.changeStatusAble = true
      this.other_form.order_id = order_id
      this.other_form.status = row.status
      this.other_form.contract_outcome = row.contract_outcome
      this.other_form.contract_income = row.contract_income
      this.other_form.contract_income_date = row.contract_income_date
      this.other_form.contract_outcome_date = row.contract_outcome_date
    },
    shareholder(order_id, row) {
      this.shareholderAble = true
      this.shareholder_from.order_id = order_id
      this.getShareHolder(order_id)
    },
    incidental(order_id, row) {
      this.incidentalAble = true
      this.other_form.order_id = order_id
      this.other_form.incidental_money = row.incidental_money
    },
    desc(order_id, row) {
      this.descAble = true
      this.other_form.order_id = order_id
      this.other_form.desc = row.descript
    },
    returnOrderSubmit() {
      returnOrderSubmit(this.form).then(response => {
        this.$notify({
          title: '提示',
          message: '修改成功',
          type: 'success',
          duration: 2000,
          onClose: this.getList()
        })
        this.returnOrderAble = false
      })
    },

    orderShareHolderSet() {
      orderShareHolderSet(this.shareholder_from).then(response => {
        if (response.code == 200) {
          this.$notify({
            title: '提示',
            message: response.msg,
            type: 'success',
            duration: 2000,
            onClose: this.getList()
          })
          this.shareholderAble = false
        } else {
          this.$notify({
            title: '提示',
            message: response.msg,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    serverAllMoneySubmit(lab) {
      this.other_form.lab = lab
      serverAllMoneySubmit(this.other_form).then(response => {
        this.$notify({
          title: '提示',
          message: '添加成功',
          type: 'success',
          duration: 2000,
          onClose: this.getList()
        })
        this.outcomeInputAble = false
        this.incidentalAble = false
        this.descAble = false
      })
    },
    serverAllMoneySubmit(lab) {
      this.other_form.lab = lab
      serverAllMoneySubmit(this.other_form).then(response => {
        this.$notify({
          title: '提示',
          message: '添加成功',
          type: 'success',
          duration: 2000,
          onClose: this.getList()
        })
        this.outcomeInputAble = false
        this.incidentalAble = false
        this.changeStatusAble = false
        this.descAble = false
      })
    },
    handleFilter() {
      const admin_id = this.$refs.admini.$data.listQuery.admin_id
      this.listQuery.logistics_admin_id = admin_id
      this.listLoading = true
      this.listQuery.page = 1
      this.getList()
    },
    plan(order_id) {
      this.dialogPlanAble = true
      this.planQuery.order_id = order_id
      this.planList()
    },

    excelout() {
      this.listLoading = true
      this.listQuery.page = 1
      this.listQuery.limit = this.total
      exceloutfinance(this.listQuery).then(response => {
        this.listLoading = false
        const filepath = response.data.path
        window.location.href = filepath
      })
    },

    getCompanyList() {
      merchantListOnlyMerchant(this.listMerchantQuery).then(response => {
        this.company_list = response.data.company
        this.sale_list = response.data.sale.data
      })
    },
    toPayment(order_id) {
      this.$router.push('/finance/customerpayment/' + order_id)
    },

    handleRecord(order_id) {
      console.log(order_id)
      this.dialogStatus = 'record'
      this.dialogRecordVisible = true
      this.listRecordQuery.order_id = order_id
      fetchOrderRecordListByOrderId(this.listRecordQuery).then(res => {
        this.record_list = res.data.list
        this.recordTotal = res.data.count
        setTimeout(() => {
          this.listRecordLoading = false
        }, 1.0 * 1000)
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.s == 1) {
        return 'success-row'
      } else if (row.s == 2) {
        return 'warning-row'
      } else if (row.s == 3) {
        return 'default-row'
      }
      return ''
    },
    uploadSuccessContract(res, file){
          let file_contract = {name:res.data.attach_id.name,url:res.data.attach_id.path,id:res.data.attach_id.id}
          this.fileListContract.push(file_contract)
      },
      handleRemoveContract(file) {
        let i = this.fileListContract.indexOf(file)
    
        this.fileListContract.splice(i,1);
      },
      handleRemove(file) {
        let i = this.indexOf(file)
       //console.log(fileListContract);return;
        this.fileList.splice(i,1);
      },
      handlePreview(file) {
        //console.log(file);
      },
      uploadSuccess(res, file) {
        
        //this.add_form.images += ',' + res.data.attach_id.id

        let file_a = {name:res.data.attach_id.name,url:res.data.attach_id.path,id:res.data.attach_id.id}
        this.fileList.push(file_a)
        //console.log(this.fileList);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },

  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    white-space: nowrap;
  }
  td{padding: 0;}
  select{
    width:100px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    float: left;
  }
   .el-table .warning-row {
      background: orangered;
    }
    .el-table .tips-row {
      background:goldenrod;
    }

  .el-table .success-row {
    background: #98dd72;
  }
  .el-table .default-row {
    background: #ccc;
  }
  .collectcss{margin-top:7px;color:#999;font-size:14px}
.el-table .warning-row {
      background: orangered;
    }

  .el-table .success-row {
    background: #98dd72;
  }
  .item {
  margin-top: 10px;
}
.flowtable{
    width: 80%;margin-left: 10%;
    border: 1px solid #eee;margin-top: 20px;  border-collapse:collapse;
  }
  .flowtable tr {height: 40px;}
  .flowtable td,.flowtable th{
    text-align: center;
    border-collapse:collapse;border: 1px solid #eee;
  }
  .l_title {
    font-size: 14px;
    font-weight: 700;
    margin-top:20px
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .img_box {
    width: 150px;
    height: 150px;
    margin-left: 16px;
    float: left;
    position: relative;
    margin-top: 20px;
  }
  @media (max-width: 768px) {
  .create {
    width: 100%;
  }
  
}
@media (min-width: 768px) {
  .create {
    width: 1000px;
  }
  }
</style>
